package com.shujia.flink.state;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Properties;

public class Demo05FilterExactlyOnce {
    public static void main(String[] args) throws Exception {
        // 1、初始化环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        KafkaSource<String> kafkaSource = KafkaSource
                .<String>builder() // 指定Kafka中每条数据的格式
                .setBootstrapServers("master:9092,node1:9092,node2:9092") // 设置Kafka集群的地址
                .setTopics("word01") // 指定Topic
                .setGroupId("my-group-0") // 指定消费者组ID
                // 设置初始的偏移量 earliest：从最早开始消费  latest：从最新的消息开始消费
                // 当消费的偏移量做了CK之后，指定为earliest也会从提交的偏移量开始继续往后消费
                .setStartingOffsets(OffsetsInitializer.earliest())
                .setValueOnlyDeserializer(new SimpleStringSchema()) // 指定如何去解析Kafka中过来的每一条数据
                .build();

        // 默认情况下Kafka Source的并行度等于Topic的分区数
        DataStreamSource<String> kafkaDS = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafkaSource");


        SingleOutputStreamOperator<String> filterDS = kafkaDS.filter(word -> !"java".equals(word));

        Properties prop = new Properties();
        /**
         * Flink会将Kafka写的事务的超时时间设置为1小时，大于KafkaBroker的15min
         */
        prop.setProperty("transaction.timeout.ms",String.valueOf(10*60*1000));

        KafkaSink<String> kafkaSink = KafkaSink
                .<String>builder()
                .setBootstrapServers("master:9092,node1:9092,node2:9092")
                .setKafkaProducerConfig(prop)
                // 指定数据序列化的方式
                .setRecordSerializer(
                        KafkaRecordSerializationSchema
                                .builder()
                                .setTopic("out01") // 指定Topic
                                .setValueSerializationSchema(new SimpleStringSchema())
                                .build()
                )
                // 设置写入数据的语义
                // 通过CK及Kafka的写入操作构成一个事务来保证EXACTLY_ONCE
                .setDeliverGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
                .build();

        filterDS.sinkTo(kafkaSink);
        env.execute();

    }
}
